//
//  WBNetWorkSessionManager.swift
//  GitWeibo
//
//  Created by 胡金东 on 2017/5/27.
//  Copyright © 2017年 胡金东. All rights reserved.
//

import UIKit
import AFNetworking


enum WBHTTPMethod {
    case GET
    case POST
}

/// - 网络管理工具
class WBNetWorkSessionManager: AFHTTPSessionManager {
    /// - swift 单例
    /// - 静态 不可变
//    static let NetWorkshared = WBNetWorkSessionManager()
    static let NetWorkshared = { () -> WBNetWorkSessionManager in 
        /// - 实例化对象
        let instance = WBNetWorkSessionManager()
        /// - 设置响应反应序列化支持数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        /// - 返回对象
        return instance
    }
    /// - 用户账户懒加载属性
    lazy var account = WBAccountModel()

     /// - 用户登录标记
    var userLogon : Bool {
        
        return account.access_token != nil
    }
    
    
    
    
    //TODO: - 封装token网络请求
    func tokenRequest(method:WBHTTPMethod,URLString:String,parameters:[String:Any]?,completion: @escaping ( _ json:Any?, _ isSuccess:Bool) -> ()) -> () {
        
        /// - 1.判断token是否有值
        guard let token = account.access_token else {
            
            print("没有token 需要登录")
            /// - 发送需要登录通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: self)
            
            completion(nil,false)
            return
        }
        /// - 2.判断字典是否nil，如果为nil，应该新建一个字典
        var parameters = parameters
        if parameters == nil {
            /// - 实例化一个字典
            parameters = [String:Any]()
        }
        /// - 这个地方parameters一定有值，可以用强行解包（！）
        parameters!["access_token"] = token
        
        
        /// - 调用网络请求
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    //TODO: - 封装AFN GET/POST 请求
    /// 封装AFN GET/POST 请求
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion: 完成回调[json(字典/数组),是否成功]
    func request(method:WBHTTPMethod,URLString:String,parameters:[String:Any]?,completion: @escaping ( _ json:Any?, _ isSuccess:Bool) -> ()){
        /// - 闭包 回调
        /// - 成功回调
        let success = {
            (task: URLSessionDataTask, json: Any?)->() in
            completion(json ,true)
        }
        /// - 失败回调
        let failure = {
            (task:URLSessionDataTask?,error:Error) ->() in
            
            /// - 针对 403 处理用户 token 过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                
                 NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: "bad token")
            }
            
            print("网络请求错误\(error)")
            completion(nil,false)
        }
        
        if method == .GET {
            
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        
    }

}
